package com.onlyphoto.onlymall.widget;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.onlyphoto.onlymall.R;
import com.bumptech.glide.Glide;
import com.onlyphoto.onlymall.bean.request.CartGoodsBean;
import com.onlyphoto.onlymall.bean.response.GoodsDetailsBean;
import com.onlyphoto.onlymall.interfaces.SoftKeyBoardListener;
import com.onlyphoto.onlymall.mvp.view.activity.LoginActivity;
import com.onlyphoto.onlymall.mvp.view.activity.OrderConfirmActivity;
import com.onlyphoto.onlymall.mvp.view.adapter.ColorAdapter;
import com.onlyphoto.onlymall.mvp.view.adapter.SizeAdapter;
import com.onlyphoto.onlymall.mvp.view.adapter.StyleAdapter;
import com.onlyphoto.onlymall.utils.ConfigUtil;

import java.util.ArrayList;


/**
 * 商品规格选择器
 *
 * Created by gaochujia on 2019-08-21.
 */
public class StylePopupView extends PopupWindow implements View.OnClickListener{

    private View mPopView;

    private ConstraintLayout clStyle;
    private ImageView close, goodsImg;
    private TextView goodsName, styleTitle, colorTitle, sizeTitle, styleSelected, reserve, addToCart, shopNow;
    private RecyclerView rvStyle, rvColor, rvSize;
    private LinearLayout llSingle, llDouble;
    private AmountView account;
    private Activity mActivity;

    private GoodsDetailsBean bean;

    private FlexboxLayoutManager styleLayoutManager, colorLayoutManager, sizeLayoutManager;
    private StyleAdapter styleAdapter;
    private ColorAdapter colorAdapter;
    private SizeAdapter sizeAdapter;

    private int colorId = 0;
    private int lastPosition = 0;
    private String styleName = "";
    private String colorName = "";
    private String sizeName = "";

    public static final int LEFT = 100;
    public static final int RIGHT = 200;
    public static final int DOUBLE = 300;
    public static final int SURE = 400;

    //规格选择完成的监听
    private OnSelectFinishedListener mListener;

    public StylePopupView(Context mContext) {
        super(mContext);
        mActivity = (Activity) mContext;
        init(mContext);
        setPopupWindow();
    }

    //初始化
    private void init(Context context) {
        mPopView = LayoutInflater.from(context).inflate(R.layout.style_select, null);
        clStyle = mPopView.findViewById(R.id.cl_style);
        close = mPopView.findViewById(R.id.close);
        goodsImg = mPopView.findViewById(R.id.goods_img);
        goodsName = mPopView.findViewById(R.id.goods_name);
        styleSelected = mPopView.findViewById(R.id.style_selected);
        reserve = mPopView.findViewById(R.id.reserve);
        rvStyle = mPopView.findViewById(R.id.rv_style);
        rvColor = mPopView.findViewById(R.id.rv_color);
        rvSize = mPopView.findViewById(R.id.rv_size);
        styleTitle = mPopView.findViewById(R.id.style_title);
        colorTitle = mPopView.findViewById(R.id.color_title);
        sizeTitle = mPopView.findViewById(R.id.size_title);
        llSingle = mPopView.findViewById(R.id.ll_single);
        llDouble = mPopView.findViewById(R.id.ll_double);
        addToCart = mPopView.findViewById(R.id.add_to_cart);
        shopNow = mPopView.findViewById(R.id.shop_now);
        account = mPopView.findViewById(R.id.amount_view);
        styleLayoutManager = new FlexboxLayoutManager(context);
        colorLayoutManager = new FlexboxLayoutManager(context);
        sizeLayoutManager = new FlexboxLayoutManager(context);
        styleAdapter = new StyleAdapter();
        colorAdapter = new ColorAdapter();
        sizeAdapter = new SizeAdapter();
        rvStyle.setAdapter(styleAdapter);
        rvColor.setAdapter(colorAdapter);
        rvSize.setAdapter(sizeAdapter);
        rvStyle.setLayoutManager(styleLayoutManager);
        rvColor.setLayoutManager(colorLayoutManager);
        rvSize.setLayoutManager(sizeLayoutManager);
    }

    @SuppressLint("SetTextI18n")
    private void setPopupWindow() {
        this.setContentView(mPopView);// 设置View

        // 点击其他区域关闭
        this.setFocusable(true);
        this.setOutsideTouchable(true);
        this.setAnimationStyle(R.style.anim_bottom);

        this.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        this.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);// 设置弹出窗口的宽
        this.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);// 设置弹出窗口的高
        this.setBackgroundDrawable(new ColorDrawable(0x00000000));// 设置背景透明
        Window window = mActivity.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();

        //退出popupWindow时显示父控件原来的颜色
        this.setOnDismissListener(() -> {
            lp.alpha = 1.0f;
            window.setAttributes(lp);
        });
        close.setOnClickListener(this);
        addToCart.setOnClickListener(this);
        shopNow.setOnClickListener(this);

        onKeyBoardListener();

        styleAdapter.setOnItemClickListener((position, name) -> {
            getReserve(0, position);
            styleName = name;
            if (!name.equals("")) {
                styleSelected.setText("已选：" + name);
                addToCart.setEnabled(true);
                shopNow.setEnabled(true);
            } else {
                styleSelected.setText("请选择 款式");
                addToCart.setEnabled(false);
                shopNow.setEnabled(false);
            }
        });

        colorAdapter.setOnItemClickListener((id, name) -> {
            loadSize(id);
            getReserve(id, lastPosition);
            colorId = id;
            colorName = name;
            if (name.equals("")) {
                addToCart.setEnabled(false);
                shopNow.setEnabled(false);
            }
            if (name.equals("") && !sizeName.equals("")) {
                styleSelected.setText("请选择 颜色");
            } else if (!name.equals("") && sizeName.equals("")) {
                styleSelected.setText("请选择 尺寸");
            } else if (sizeName.equals("") && name.equals("")) {
                styleSelected.setText("请选择 颜色 尺寸");
            } else {
                styleSelected.setText("已选：" + name + sizeName);
                addToCart.setEnabled(true);
                shopNow.setEnabled(true);
            }
        });

        sizeAdapter.setOnItemClickListener((position, name) -> {
            getReserve(colorId, position);
            sizeName = name;
            if (name.equals("")) {
                addToCart.setEnabled(false);
                shopNow.setEnabled(false);
            }
            if (name.equals("") && !colorName.equals("")) {
                styleSelected.setText("请选择 尺寸");
            } else if (!name.equals("") && colorName.equals("")) {
                styleSelected.setText("请选择 颜色");
            } else if (colorName.equals("") && name.equals("")) {
                styleSelected.setText("请选择 颜色 尺寸");
            } else {
                styleSelected.setText("已选：" + colorName + name);
                addToCart.setEnabled(true);
                shopNow.setEnabled(true);
            }
        });
    }

    private void onKeyBoardListener() {
        SoftKeyBoardListener.setListener(mActivity, new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {
            }

            @Override
            public void keyBoardHide(int height) {
                clStyle.requestFocus();
            }
        });
    }

    public void setButton(int mode) {
        if (mode == LEFT) {
            addToCart.setVisibility(View.VISIBLE);
            shopNow.setVisibility(View.GONE);
        }
        if (mode == RIGHT) {
            addToCart.setVisibility(View.GONE);
            shopNow.setVisibility(View.VISIBLE);
        }
        if (mode == DOUBLE) {
            addToCart.setVisibility(View.VISIBLE);
            shopNow.setVisibility(View.VISIBLE);
        }
        if (mode == SURE) {
            addToCart.setVisibility(View.VISIBLE);
            shopNow.setVisibility(View.GONE);
            addToCart.setText("确定");
        }
    }

    public void setUpdateData() {

    }

    @SuppressLint("SetTextI18n")
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    public void loadData(GoodsDetailsBean bean, String styleStr, int buyNum){
        this.bean = bean;

        Glide.with(mPopView.getContext()).load(bean.getFront_img_arr().get(0)).placeholder(R.mipmap.img_default).into(goodsImg);
        goodsName.setText(bean.getTitle());
        account.setAmount(buyNum);
        if (!styleStr.equals("")) {
            String[] styleList = styleStr.split(";");
            if (styleList.length == 1) {
                styleName = styleList[0];
                colorName = "";
                sizeName = "";
            } else {
                styleName = "";
                colorName = styleList[0];
                sizeName = styleList[1];
            }
        }
        if (bean.getAttribute_set() == 1) {
            llSingle.setVisibility(View.VISIBLE);
            llDouble.setVisibility(View.GONE);
            styleTitle.setText(bean.getStyle_title());
            if (bean.getStyle_arr() != null) {
                styleAdapter.setItemData(bean.getStyle_arr(), styleName);
                if (styleName.equals("")) {
                    styleName = bean.getStyle_arr().get(0).getName();
                    getReserve(0, 0);
                } else {
                    for (GoodsDetailsBean.Style style: bean.getStyle_arr()) {
                        if (style.getName().equals(styleName)) {
                            getReserve(0, bean.getStyle_arr().indexOf(style));
                        }
                    }
                }
                styleSelected.setText("已选：" + styleName);
            }
        }
        if (bean.getAttribute_set() == 2) {
            llSingle.setVisibility(View.GONE);
            llDouble.setVisibility(View.VISIBLE);
            colorTitle.setText(bean.getColor_title());
            sizeTitle.setText(bean.getSize_title());
            if (bean.getColor_arr() != null) {
                colorAdapter.setItemData(bean.getColor_arr(), colorName);
                if (colorName.equals("")) {
                    colorId = bean.getColor_arr().get(0).getId();
                    colorName = bean.getColor_arr().get(0).getName();
                } else {
                    for (GoodsDetailsBean.Color color: bean.getColor_arr()) {
                        if (color.getName().equals(colorName)) {
                            colorId = color.getId();
                            lastPosition = bean.getColor_arr().indexOf(color);
                        }
                    }
                }
            }
            if (bean.getSize_arr().get(bean.getColor_arr().get(0).getId()) != null) {
                sizeAdapter.setItemData(bean.getSize_arr().get(bean.getColor_arr().get(0).getId()),true, sizeName);
                if (sizeName.equals("")) {
                    lastPosition = 0;
                    sizeName = bean.getSize_arr().get(bean.getColor_arr().get(0).getId()).get(0).getName();
                } else {
                    for (GoodsDetailsBean.Size size: bean.getSize_arr().get(colorId)) {
                        if (size.getName().equals(sizeName)) {
                            lastPosition = bean.getSize_arr().get(colorId).indexOf(size);
                        }
                    }
                }
            }
            getReserve(colorId, lastPosition);
            styleSelected.setText("已选：" + colorName + sizeName);
        }
    }

    private void loadSize(int id) {
        if (bean.getSize_arr().get(id) != null) {
            sizeAdapter.setItemData(bean.getSize_arr().get(id), false, "");
        }
    }

    private void getReserve(int colorId, int position){
        if (bean.getAttribute_set() == 1) {
            reserve.setText("库存" + bean.getStyle_arr().get(position).getGoods_num());
        } else {
            reserve.setText("库存"+ bean.getSize_arr().get(colorId).get(position).getGoods_num());
        }
    }

    @Override
    public boolean isShowing() {
        if (bean != null) {
            if (bean.getAttribute_set() == 1) {
                if (styleAdapter.isChoose()) {
                    addToCart.setEnabled(true);
                    shopNow.setEnabled(true);
                } else {
                    addToCart.setEnabled(false);
                    shopNow.setEnabled(false);
                }
            }
            if (bean.getAttribute_set() == 2) {
                if (colorAdapter.isChoose() && sizeAdapter.isChoose()) {
                    addToCart.setEnabled(true);
                    shopNow.setEnabled(true);
                } else {
                    addToCart.setEnabled(false);
                    shopNow.setEnabled(false);
                }
            }
        }
        return super.isShowing();
    }

    private CartGoodsBean cartGoodsBean;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.close:
                dismiss();
                break;
            case R.id.add_to_cart:
                if (!ConfigUtil.instance.getLoginStatus()) {
                    mPopView.getContext().startActivity(new Intent(mPopView.getContext(), LoginActivity.class));
                    return;
                }
                cartGoodsBean = new CartGoodsBean();
                cartGoodsBean.setGoods_id(bean.getId());
                cartGoodsBean.setBuy_num(account.getAmount());
                cartGoodsBean.setStyle(styleName);
                cartGoodsBean.setColor(colorName);
                cartGoodsBean.setSize(sizeName);
                mListener.finished(cartGoodsBean);
                dismiss();
                break;
            case R.id.shop_now:
                if (!ConfigUtil.instance.getLoginStatus()) {
                    mPopView.getContext().startActivity(new Intent(mPopView.getContext(), LoginActivity.class));
                    return;
                }
                cartGoodsBean = new CartGoodsBean();
                cartGoodsBean.setImg(bean.getFront_img_arr().get(0));
                cartGoodsBean.setName(bean.getTitle());
                cartGoodsBean.setPrice(bean.getPrice_now());
                cartGoodsBean.setGoods_id(bean.getId());
                cartGoodsBean.setBuy_num(account.getAmount());
                cartGoodsBean.setStyle(styleName);
                cartGoodsBean.setColor(colorName);
                cartGoodsBean.setSize(sizeName);
                cartGoodsBean.setAllow_user_img(bean.getAllow_user_img());
                if (bean.getGift_arr() != null) {
                    cartGoodsBean.setGift_title(bean.getGift_arr().getTitle());
                }
                ArrayList<CartGoodsBean> list = new ArrayList<>();
                list.add(cartGoodsBean);
                mPopView.getContext().startActivity(new Intent(mPopView.getContext(), OrderConfirmActivity.class)
                        .putExtra("goodsList", list)
                        .putExtra("fromDetails", true));
                dismiss();
                break;
        }
    }

    public void setFinishedListener(OnSelectFinishedListener listener){
        this.mListener = listener;
    }

    public interface OnSelectFinishedListener{
        void finished(CartGoodsBean bean);
    }
}
